package com.restaurant.application.util.counter;

import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.restaurant.application.util.counter.support.AbstractCounter;
import com.restaurant.application.util.counter.support.CounterData;
import com.restaurant.application.util.counter.support.CounterValue;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Objects;

public class CounterImpl extends AbstractCounter {

    private static final ZoneId BEI_JING_TIME = ZoneId.of("Asia/Shanghai");

    @Override
    public Integer get(String name) {
        CounterData data = getData();
        if (Objects.isNull(data.getData().get(name))) {
            data.getData().put(name, this.init());
        }
        CounterValue value = data.getData().get(name);
        Integer i = value.getIndex();
        LocalDate localDate = Instant.ofEpochMilli(value.getTime()).atZone(BEI_JING_TIME).toLocalDate();
        if (!LocalDate.now(BEI_JING_TIME).equals(localDate)) {
            i = 0;
        }
        i++;
        value.withIndex(i);
        value.withTime(getCurrentMillisecond());
        data.getData().put(name, value);
        return i;
    }

    private CounterValue init() {
        return new CounterValue(0, getCurrentMillisecond());
    }

    private long getCurrentMillisecond() {
        return Instant.now().toEpochMilli();
    }

    @Override
    public View getFullView() {
        return null;
    }

    @Override
    public View getViewLead(ViewSpec viewSpec) {
        return null;
    }
}
